<template>
    <div class="create_service">
        <div class="text_title mb20 ml10">新建服务</div>
        <ElForm :model="ruleForm" :rules="rules" label-width="80px" class="demo-ruleForm" label-position="right">
            <ElFormItem label="服务名称" prop="serviceName">
                <ElInput class="w600" v-model="ruleForm.serviceName" placeholder="请输入服务名"></ElInput>
            </ElFormItem>
            <ElFormItem label="服务描述" prop="serviceDesc">
                <ElInput
                    type="textarea"
                    placeholder="请输入服务描述"
                    class="w600"
                    :autosize="{ minRows: 4 }"
                    v-model="ruleForm.serviceDesc"
                ></ElInput>
            </ElFormItem>
            <ElFormItem label="展示价格" prop="displayPrice">
                <ElInput placeholder="请输入展示价格" class="w600" v-model.number="ruleForm.displayPrice"></ElInput>
            </ElFormItem>
        </ElForm>
        <div class="ml500">
            <ElButton class="w80 but_cancel" size="small" @click="goBack">取消</ElButton>
            <ElButton @click="onSubmit" class="w80 but_confirms" size="small">确定</ElButton>
        </div>
        <div class="mt30 dashed_line"></div>
        <div v-if="route.query.editsID">
            <div class="mt30">
                <ElButton @click="showCreate()" class="but_create" size="small">新建规格</ElButton>
            </div>
            <ElTable v-if="specs && specs.length > 0" :data="specs" class="w_100">
                <ElTableColumn prop="name" label="规格名称" width="180" />
                <ElTableColumn prop="options" label="规格类">
                    <template #default="scope">
                        <div>
                            <span class="mr5" v-for="(data, index) in scope.row.options" :key="index">
                                <el-tag class="mx-1" size="small">{{ data.optionName }}</el-tag>
                            </span>
                        </div>
                    </template>
                </ElTableColumn>
                <ElTableColumn label="操作">
                    <template #default="scope">
                        <ElButton type="text" size="small" @click="deleteSpec(scope.row)">删除</ElButton>
                    </template>
                </ElTableColumn>
            </ElTable>
            <div class="mt30">
                <ElButton @click="showSkusCreate()" class="but_create" size="small">添加价格</ElButton>
            </div>
            <ElTable v-if="skus && skus.length > 0" :data="skus" class="w_100">
                <template v-for="item in specs" :key="item.name">
                    <ElTableColumn :prop="item.name" :label="item.name" width="180" />
                </template>
                <ElTableColumn prop="price" label="价格(元)">
                    <template #default="scope">
                        <span>{{ scope.row.price }}</span>
                    </template>
                </ElTableColumn>
                <ElTableColumn label="操作">
                    <template #default="scope">
                        <ElButton type="text" size="small" @click="editSpec(scope.row)">编辑</ElButton>
                        <ElButton type="text" size="small" @click="deleteSku(scope.row)">删除</ElButton>
                    </template>
                </ElTableColumn>
            </ElTable>
        </div>
        <ElDialog v-model="createSpecificationsVisible" title="添加规格" width="30%">
            <ElForm :label-width="'100px'">
                <ElFormItem label="规格名称：">
                    <ElInput class="w300" v-model="attributeName" placeholder="请输入规格"></ElInput>
                </ElFormItem>
                <ElFormItem label="规格分类：">
                    <div v-for="(item, index) in attributeValue" :key="item.key">
                        <ElInput class="w300" v-model="item.value"></ElInput>
                        <ElButton v-if="index === 0" class="ml20" type="text" @click="addEl()">新增</ElButton>
                        <ElButton class="ml20" type="text" @click="del(item.key)" v-if="attributeValue.length > 1">
                            删除
                        </ElButton>
                    </div>
                </ElFormItem>
            </ElForm>
            <template #footer>
                <span class="dialog-footer">
                    <ElButton class="but_cancel" @click="cancelCreate" size="small">取消</ElButton>
                    <ElButton class="but_confirms" @click="createSpecifications" size="small">确定</ElButton>
                </span>
            </template>
        </ElDialog>
        <ElDialog v-model="createSkusVisible" title="价格配置" width="30%">
            <ElForm :label-width="'100px'">
                <ElFormItem v-for="option in serviceOptionList" :key="option.name" :label="option.name + ':'">
                    <el-select class="w300" v-model="option.value" placeholder="请选择">
                        <ElOption
                            v-for="item in option.options"
                            :key="item.optionId"
                            :label="item.optionName"
                            :value="item.optionId"
                        ></ElOption>
                    </el-select>
                </ElFormItem>
                <ElFormItem label="价格：">
                    <ElInput class="w300" v-model="ruleForm.price" placeholder="请输入价格"></ElInput>
                </ElFormItem>
            </ElForm>
            <template #footer>
                <span class="dialog-footer">
                    <ElButton class="but_cancel" @click="cancelCreate" size="small">取消</ElButton>
                    <ElButton class="but_confirms" @click="createSkus" size="small">确定</ElButton>
                </span>
            </template>
        </ElDialog>
    </div>
</template>

<script setup lang="ts">
import { useRouter, useRoute } from 'vue-router';
import { ref, reactive, Ref } from 'vue';
import { ElMessage } from 'element-plus';
import {
    getServiceById,
    createService,
    deleteSpecification,
    createServiceSpecification,
    createServiceSelection,
    deleteServiceSkuBySkuId,
    updateServiceSelection,
    updateService,
} from '@/api/api.query.util';

const createSpecificationsVisible = ref(false);
const createSkusVisible = ref(false);
const router = useRouter();
const route = useRoute();
const ruleForm = reactive({
    serviceName: '',
    serviceDesc: '',
    displayPrice: '',
    price: '',
    editSkuId: '',
});
const rules = reactive({
    serviceName: [
        {
            required: true,
            message: '服务名称不能为空',
            trigger: 'blur',
        },
    ],
    displayPrice: [
        {
            required: true,
            message: '展示价格不能为空',
            trigger: 'blur',
        },
        {
            type: 'number',
            message: '价格必须是数字'
        },
    ],
});
const specs: Ref<
    Array<{
        name: string;
        options: any;
    }>
> = ref([]);
const skus = ref([]);
const attributeName = ref('');
const attributeValue = ref([
    {
        key: new Date().getTime(),
        value: '',
    },
]);
const serviceOptionList = ref([]);
if (route.query.editsID) {
    getServiceDetails();
}
function getServiceDetails() {
    getServiceById({
        method: 'post',
        data: {
            serviceId: route.query.editsID,
        },
    }).then((res) => {
        specs.value = res.result.specs || [];
        if (specs.value.length > 0) {
            serviceOptionList.value = specs.value.map((item) => ({
                name: item.name,
                value: '',
                selectionId: '',
                options: item.options,
            }));
        }
        if (res.result.skus) {
            res.result.skus.forEach((item) => {
                item.selections.forEach((a) => {
                    item[a.specName] = a.optionName;
                });
            });
        }
        skus.value = res.result.skus;
        ruleForm.serviceName = res.result.serviceName;
        ruleForm.serviceDesc = res.result.serviceDesc;
        ruleForm.displayPrice = res.result.displayPrice;
    });
}
function deleteSpec(row: any) {
    deleteSpecification({
        method: 'delete',
        data: {
            specId: row.specId,
        },
    }).then((res) => {
        if(res.code === 200){
            ElMessage.success('删除成功');
            getServiceDetails();
        }
    });
}
function deleteSku(row: any) {
    deleteServiceSkuBySkuId({
        method: 'delete',
        data: {
            skuId: row.skuId,
        },
    }).then((res) => {
        if(res.code === 200){
            ElMessage.success('删除成功');
            getServiceDetails();
        }
    });
}
function onSubmit() {
    if (!ruleForm.serviceName) {
        return;
    }
    if (!ruleForm.displayPrice || !Number.isInteger(ruleForm.displayPrice)) {
        return;
    }
    if (route.query.editsID) {
        updateService({
            method: 'post',
            data: { ...ruleForm, ...{ serviceId: route.query.editsID } },
        }).then((res) => {
            if(res.code === 200){
                ElMessage.success('修改成功');
                goBack();
            }
        });
    } else {
        createService({
            method: 'post',
            data: ruleForm,
        }).then((res) => {
            if(res.code === 200){
                ElMessage.success('创建成功');
                goBack();
            }
        });
    }
}
function cancelCreate() {
    createSpecificationsVisible.value = false;
    createSkusVisible.value = false;
}
function showCreate() {
    attributeName.value = '';
    attributeValue.value = [
        {
            key: new Date().getTime(),
            value: '',
        },
    ];
    createSpecificationsVisible.value = true;
}
function createSkus() {
    if (ruleForm.editSkuId) {
        updateServiceSelection({
            method: 'post',
            data: {
                skuId: ruleForm.editSkuId,
                price: ruleForm.price,
                optionProperties: serviceOptionList.value.map((item) => ({
                    optionId: item.value,
                    selectionId: item.selectionId,
                })),
            },
        }).then((res) => {
            if(res.code === 200){
                ElMessage.success('修改成功');
                getServiceDetails();
            }
        });
        ruleForm.editSkuId = '';
    } else {
        createServiceSelection({
            method: 'post',
            data: {
                serviceId: route.query.editsID,
                price: ruleForm.price,
                optionIds: serviceOptionList.value.map((item) => item.value),
            },
        }).then((res) => {
            if(res.code === 200){
                ElMessage.success('新增成功');
                getServiceDetails();
            }
            
        });
    }
    ruleForm.price = '';
    createSkusVisible.value = false;
}
function createSpecifications() {
    const valueArr = attributeValue.value.map((item: any) => item.value).filter((s) => s && s.trim());
    if (!attributeName.value) {
        ElMessage.warning('规格名称未填写');
        return;
    }
    if (valueArr.length === 0) {
        ElMessage.warning('规格类至少填写一个');
        return;
    }
    if (new Set(valueArr).size !== valueArr.length) {
        ElMessage.warning('规格类重复');
        return;
    }
    createServiceSpecification({
        method: 'post',
        data: {
            serviceId: route.query.editsID,
            name: attributeName.value,
            serviceOptionList: valueArr,
        },
    }).then((res) => {
        if(res.code === 200){
            ElMessage.success('新增成功');
            getServiceDetails();
        }
    });
    createSpecificationsVisible.value = false;
    attributeName.value = '';
    attributeValue.value = [
        {
            key: new Date().getTime(),
            value: '',
        },
    ];
}
function addEl() {
    attributeValue.value.push({
        key: new Date().getTime(),
        value: '',
    });
}
function del(key: any) {
    attributeValue.value.forEach(
        (
            item: {
                key: any;
            },
            index: number,
        ) => {
            if (item.key === key) {
                attributeValue.value.splice(index, 1);
            }
        },
    );
}
function showSkusCreate() {
    createSkusVisible.value = true;
}
function editSpec(row: any) {
    createSkusVisible.value = true;
    ruleForm.editSkuId = row.skuId;
    ruleForm.price = row.price;
    serviceOptionList.value.forEach((item) => {
        const option = row.selections.find((a) => a.optionName === row[item.name]);
        item.value = option.optionId;
        item.selectionId = option.selectionId;
    });
}

function goBack() {
    router.push({ name: '/home/service-management' });
}
</script>

<style lang="scss" scoped>
.create_service {
    padding: 25px 30px 20px 20px;
    background-color: var(--bg-default);
}
.text_title {
    font-size: var(--font-size);
    color: var(--text-primary);
}
.but_confirms {
    background-color: var(--btn_default);
    border-radius: 4px;
    color: var(--text-default);
}

.dashed_line {
    border-top: 1px dashed #dfe1e6;
}
.w300 {
    color: #666666;
}
.but_cancel {
    border-radius: 4px;
    color: var(--text-secondary);
}
</style>
